<template>
  <div style="">
    <div v-if="articleObj.status == '0' || articleObj.status == '1'">
      <el-row class="edit-head">
        <el-col :span="12">
          <div class="">
            <el-input
              placeholder="请输入标题"
              v-model="article_title"
              clearable>
            </el-input>
          </div>
        </el-col>
        <el-col :span="12">
          <div class="" style="position: relative;">
            <div class="btn-group">
              <!-- <el-button class="btn" type="primary" @click="preview">预览</el-button> -->
              <el-button class="btn" type="primary" @click="publish">发布</el-button>
            </div>
          </div>
        </el-col>
      </el-row>
      <Editor
        :locale="zhHans"
        :value="value" 
        :plugins="plugins" 
        @change="handleChange"
        :uploadImages="(files) => uploadImages(files)"
        :handleImageUpload="(files) => uploadImages(files)"
      />
    </div>
    <div v-if="articleObj.status == '2'" >
      <el-row class="edit-head">
        <el-col :span="12">
          <div style="width: calc(100vw - 300px) !important;">
            <h1 style="background-color: white;margin: 12px 0px;width: 82%;padding: 0px 30px;">{{article_title}}</h1>
          </div>
        </el-col>
        <el-col :span="12">
          <div class="" style="position: relative;">
            <div class="btn-group">
              <el-button class="btn" type="primary" @click="toUpdate">编辑</el-button>
            </div>
          </div>
        </el-col>
      </el-row>
      <el-row class="edit-head">
        <Viewer class="content" style="
        height: 86vh;
        overflow: auto;
        background-color: #fff;
        padding: 0px 30px;
        width: 82%;" 
        :value="value" :plugins="plugins"/>
      </el-row>
    </div>
    <el-dialog class="preview-dialog"
        title="预览"
        :visible.sync="isPreview"
        width="80%"
        :before-close="closePreview">
        <h1>{{article_title == "" ? "暂无标题" : article_title}}</h1>
        <!-- 一种方式是使用id,ref 的属性，给这个div标签，把内容给插入进去 -->
        <!-- <div id="content" ref="content"></div> -->
        <!-- 另一种方式，就是用编辑器自带的 Viewer标签，只展示【看】方式的内容 -->
        <Viewer class="content" :value="value" :plugins="plugins"/>
      </el-dialog>
      <VueParticles />
  </div>
</template>

<script>
import { addNote, selectNoteById, updateNoteById } from "@/api";

import VueParticles from './comVueParticles';
import { Editor, Viewer } from '@bytemd/vue';
import gfm from '@bytemd/plugin-gfm';
import highlightssr from '@bytemd/plugin-highlight-ssr';
import highlight from '@bytemd/plugin-highlight';
import breaks from '@bytemd/plugin-breaks';
import footnotes from '@bytemd/plugin-footnotes';
import frontmatter from '@bytemd/plugin-frontmatter';
import gemoji from '@bytemd/plugin-gemoji';
import mediumZoom from '@bytemd/plugin-medium-zoom';
import * as marked from "marked";
import 'highlight.js/styles/vs.css';
// import "highlight.js/styles/monokai-sublime.css"; // 引入高亮样式 这里我用的是sublime样式
import 'bytemd/dist/index.min.css'; // 引入MD编辑器样式
import zhHans from 'bytemd/lib/locales/zh_Hans.json'; // 设置中文
import 'juejin-markdown-themes/dist/juejin.min.css'; // 使用掘金样式

const plugins = [
  gfm(),
  highlight(),
  highlightssr(),
  breaks(),
  frontmatter(),
  footnotes(),
  gemoji(),
  mediumZoom(),
]

export default {
  components: { Editor, Viewer, VueParticles },
  data() {
    return {
      value: '',
      plugins,
      zhHans,
      article_title: '',
      isPreview: false,
      articleObj: {
        status: '0', // 0：新建， 1：编辑， 2： 只读
        articleId: '000',
        user_id: '000-000-000',
      }
    };
  },
  methods: {
    handleChange(v) {
      //console.log(v)
      this.value = v
    },
    uploadImages(files) {
      // files 获取的图片文件，这里处理逻辑
      //console.log('files', files);
      // 处理图片逻辑
      // 此处的url 需要后端配合，把图片上传上去，并返回图片的地址
      return [
        {
          title: files.map((i) => i.name),
          url: "https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/69137906061d47b7b8e1e05c3791bb47~tplv-k3u1fbpfcp-watermark.awebp",
        },
      ];
    },
    preview() {
      this.isPreview = true;
      this.$nextTick(() => {
        // this.$refs.content.innerHTML =
        // this.mdToHtml(this.value);
        // marked.parse(this.value);
        // debugger;
      });
    },
    // md 转 html
    mdToHtml(mdContent) {
      marked.setOptions({
        renderer: new marked.Renderer(),
        gfm: true, // 允许 Git Hub标准的markdown
        tables: true, // 允许支持表格语法
        breaks: false, // 允许回车换行
        pedantic: false, // 不纠正原始模型任何的不良行为和错误
        sanitize: false, // 输出进行过滤（清理）
        smartLists: true, // 使用比原生markdown更时髦的列表
        smartypants: false, // 使用更为时髦的标点，比如在引用语法中加入破折号
        highlight: function (code, lang) { // 高亮显示
          const hljs = require('highlight.js');
          // hljs.highlightAll();
          const language = hljs.getLanguage(lang) ? lang : 'plaintext';
          // return hljs.highlight(code, { language }).value;
          // return hljs.highlightAuto(code).value;
          return hljs.highlight(lang, code, true).code;
        },
        langPrefix: 'hljs language-', // highlight.js css expects a top-level 'hljs' class.
      });
      return marked.parse(mdContent);
    },
    // 关闭预览
    closePreview() {
      this.isPreview = false;
    },
    // 【调接口】发布文章
    publish() {
      if (this.article_title == '') {
        this.$message.error("文章标题不能为空");
        return;
      }
      // 新增笔记
      if (this.articleObj.status == '0') {
        let params = {
          info_id: this.articleObj.user_id,
          title: this.article_title,
          content: this.value,
          // picture: '',
          is_delete: false
        };
        addNote(params).then((res) => {
          //console.log(res);
          if(res.data.code ===200){
            this.$message.success("新增成功！")
            // 跳转文章查看页
            debugger;
            this.$router.replace({ 
              path: '/articleDetail', 
              query: { 
                status: '2', 
                articleId: res.data.data._id
              }
            });
            this.$router.go(0); // 重新刷新当前页面
            // this.article_title = res.data.data.title;
            // this.value = res.data.data.content;
          }
        })
        //console.log(this.value);
        // console.log(params);
      } else if (this.articleObj.status == '1') {
        // 编辑笔记
        let data = {
          _id: this.articleObj.articleId,
          info_id: this.articleObj.user_id,
          title: this.article_title,
          content: this.value,
          // picture: '',
          is_delete: false
        };
        updateNoteById(data).then((res) => {
          //console.log(res);
          if(res.data.code ===200){
            this.$message.success("修改成功！")
            // 跳转文章查看页
            const newPage = this.$router.replace({ 
              path: '/articleDetail', 
              query: { 
                status: '2', // 只读
                articleId: this.articleObj.articleId
              }
            });
            this.$router.go(0); // 重新刷新当前页面
            // this.article_title = res.data.data.title;
            // this.value = res.data.data.content;
          }
        });
      }
      

      
    },
    // 【接口】指定文章
    loadArticle() {
      debugger;
      if (this.articleObj.articleId !== '000') {
        let articleId = this.$route.query.articleId;
        // 查询接口加载文章
        selectNoteById(articleId).then((res) => {
            if(res.data.code ===200){
              this.$message.success("笔记加载成功！");
              this.article_title = res.data.data.title;
              this.value = res.data.data.content;
            }
        });
        // this.article_title = "双击鼠标666";
        // this.value = "## 12121212 ```js <p>2323</p>```";
      }
    },
    // 【编辑】前往编辑文章页面
    toUpdate() {
      const newPage = this.$router.resolve({ 
        path: '/articleDetail', 
        query: { 
          status: '1', 
          articleId: this.articleObj.articleId 
        }
      })
      // debugger
      window.open(newPage.href,'_blank')
    },
  },
  mounted() {
    let user = window.sessionStorage.getItem('user');
    let dealUser = JSON.parse(user);
    const params = this.$route.query; // news页面接收传过来的值

    this.articleObj.user_id = dealUser._id;
    this.articleObj.status = params.status;
    this.articleObj.articleId = params.articleId;

    //console.log('this.articleObj', this.articleObj);
    this.loadArticle();
  },
}
</script>


<style lang="scss" scoped>
.edit-head{
  width: calc(100vw - 300px) !important;
  margin: 0px auto;
  height: 60px;
  line-height: 60px;
  .btn-group{
    position: absolute;
    right: 0px;
  }
}
::v-deep .bytemd {
  height: calc(100vh - 100px) !important;
  width: calc(100vw - 300px) !important;
  margin: 0px auto;
}
.preview-dialog{
  // height: 600px;
  overflow: hidden;
  ::v-deep .el-dialog__body{
    height: calc(100vh - 395px);
  }
  .content{
    // height: calc(100vh - 384px);
    // overflow-x: hidden;
    // overflow-y: auto;
    
  }
}
</style>